﻿/*
File: CRenderer.cpp
 
 Leírás:
	a renderelést végző egyke osztály

 szerző: Sipos Csaba


*/

#include "CRenderer.h"

using namespace Util;
using namespace Engine;

//inicializálás
CRenderer *CRenderer::pInstance=0;

//konstruktor
CRenderer::CRenderer()
{
  deviceLost = false;
  //megjelenítő eszköz lekérése
  pDevice = CDevice::getInstance();
	pD3DDevice=pDevice->getD3DDevice();
	screenWidth = pDevice->getScreenWidth();
	screenHeight = pDevice->getScreenHeight();

  //kezdetben nincs kamera
  pCamera = 0;

  //fény beállítása
	lightColor = D3DCOLOR_XRGB(255, 255, 255);
	lightPos = D3DXVECTOR3( -500.0f,500.f, 450.0f );	

  //Primitív inicializálás
  numPrimVertices = 0;
  numPrimIndices = 0;
  numPrimVertices = 0;
  createPrimVertexDecl();
  createPrimFX();
  pPrimVBuffer = 0;
  pPrimIBuffer = 0;
  createMeshFX();

  
  //Primitív anyagjellemzők
	primMat.ambientMat=D3DCOLOR_XRGB(200, 200, 200);
	primMat.diffuseMat=D3DCOLOR_XRGB(100, 100, 100);
	primMat.specularMat=D3DCOLOR_XRGB( 200, 200, 200 );
	primMat.specularPower = 1.0f;

  //projektciós mátrix
  buildMatProj();

  //Timer kérése
	pTimer=CTimer::getTimerInstance();
  //pTimer->update();
  //FPS kijelző létrehozása
	fps=new CFramePSecond(pD3DDevice);
  pPrimitives = 0;
  pSkyBox = new Content::CSkyBox();
  pSkyBox->setColor(100,0,100);
}
void CRenderer::destroy()
{
  if (pInstance)
  {
    delete pInstance;
    pInstance = 0;
  }
}

CRenderer::~CRenderer()
{
  pD3DDevice = 0;

}

//instance lekérdezés
CRenderer * CRenderer::getInstance()
{
	if(0==pInstance)
	{
		pInstance=new CRenderer();
	}
	return pInstance;
}

//tisztítás
void CRenderer::clean()
{	
  pPrimitives = 0;
	pD3DDevice = 0;
  pTimer = 0;
	fps->clean();
	Util::SAFE_DELETE(fps);
  SAFE_RELEASE(pPrimEffect);
  SAFE_RELEASE(pPrimVertexDecl);
  releaseBuffers();
  pSkyBox->clean();
  pSkyBox = 0;
  SAFE_RELEASE(pMeshEffect);
}


void CRenderer::buildMatProj()
{
  D3DXMatrixPerspectiveFovLH(&matProj,
                             D3DXToRadian(45),    // the horizontal field of view
                             (FLOAT)screenWidth / (FLOAT)screenHeight, // aspect ratio
                             0.1f,   // the near view-plane
                             3000.0f);    // the far view-plane

}

void CRenderer::updateMatProj()
{
  screenWidth = pDevice->getScreenWidth();
  screenHeight = pDevice->getScreenHeight();
  buildMatProj();
}

void CRenderer::setSkyBoxTexture(std::string fname)
{
  pSkyBox->loadCubeTexture(fname);
}

void CRenderer::checkDevice()
{
	if( !pD3DDevice)
	{
		LOG_ERROR("NULL Device");
		return;
	}

	HRESULT hr;
	// megjelenítés elõtt gyõzõdjünk meg arról, hogy nem vesztettük el 
	// Direct3DDevice9 eszközünket
	if( deviceLost )
	{
  	// kis késleltetés
		  Sleep( 100 );
		// A TestCooperativeLevel() hívással meggyõzõdhetünk arról, hogy 
		// a megjelenítés nem ütközik problémákba, illetve visszatérési értéke alapján
		// eldönthetjük, hogyan kezeljük a felmerült hibát
		if( FAILED( hr = pD3DDevice->TestCooperativeLevel() ) )
		{
			// az elveszett eszközt még nem lehet újraállítani a Reset() hívással
			// kicsit késõbb újra próbálkozunk (az elõbbi késleltetés is ezt a célt szolgálja)

			if( hr == D3DERR_DEVICELOST )
			{
				return;
			}

			// lehetséges az eszköz újraállítása 
			if( hr == D3DERR_DEVICENOTRESET )
			{
				// IDirect3DDevice9::Reset() elõtt fel kell szabadítani a 
				// videomemóriában lefoglalt erõforrásokat
				onLostDevice();
				// Állísuk vissza az elveszett eszközt: erre a célra kizárólag 
				// a Reset() hívás alkalmazható.
				LOG_INFO("RESET");
        hr = pDevice->resetDevice();

				// A Reset() mindaddig hibával tér vissza, míg nem szabadítjuk fel
				// az összes D3DPOOL_DEFAULT memóriaosztályba tartozó erõforrást,
				// beleértve az IDirect3DDevice9::CreateRenderTarget() és 
				// IDirect3DDevice9::CreateDepthStencilSurface() hívásokkal létrehozottakat.
				if( FAILED( hr ) )
				{
					return;
					//return false;
				}

				// Sikeresen helyreállítottuk eszközünket, úgyhogy újra le kell foglalnunk
				// a Reset() hívást megelõzõen felszabadított erõforrásokat
				onResetDevice();
			}
		}
		//return false;
		else
		{
			deviceLost = false;
		}
  }
}



//render
void CRenderer::render()
{
  if (pCamera)
  {
    pCamera->update();
  }
  else
  {
    LOG_ERROR("Nincs kamera beallitva!")
  }


	float elapsedTime=pTimer->getElapsedTime();
	fps->update(elapsedTime);

  checkDevice();
  if (deviceLost)
  {
    LOG_INFO("device lost")
    return;
  }

	// Clear the backbuffer to a blue color
	pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB( 100, 100, 100 ), 1.0f, 0 );
	pD3DDevice->Clear( 0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB( 100, 100, 100 ), 1.0f, 0 );

	
  // Begin the scene
	if(pCamera && SUCCEEDED( pD3DDevice->BeginScene() ) )
	{
		// Rendering of scene objects can happen here
    if (!pMeshes->empty())
    {
      renderMeshes();
    }

    if (!pPrimitives->empty())
    {
      renderPrimitives();	
    }

    if (pSkyBox->getCubeTexture())
    {
      renderSkyBox();
    }

    if (!pGUIObjects->empty())
    {
      renderGUI();
    }

    //frém per másodperc kirajzolása
		fps->render();
		// End the scene
		pD3DDevice->EndScene();
	}

	// Present the backbuffer contents to the display
	HRESULT hr = pD3DDevice->Present( NULL, NULL, NULL, NULL );
	if( D3DERR_DEVICELOST  == hr)
	{
			deviceLost = true;
	}
}

//elveszett eszközök esetén
void CRenderer::onLostDevice()
{
  LOG_INFO("Device Lost")
	fps->onLostDevice();
  releaseBuffers();
  pPrimVertexDecl->Release();
  pPrimEffect->Release();

  pMeshEffect->Release();

  pSkyBox->onLostDevice();

  for (std::vector<Content::CAnimatedMesh*>::iterator it = pMeshes->begin();it != pMeshes->end();++it)
  {
    (*it)->onLostDevice();
  }
  for (std::vector<GUI::CGUIObject*>::iterator it = pGUIObjects->begin();it != pGUIObjects->end();++it)
  {
    (*it)->onLostDevice();
  }

}

//ha reseteljük az eszközt
void CRenderer::onResetDevice()
{
  LOG_INFO("Device reset")
  pSkyBox->onResetDevice();
  buildPrimVertexBuffer();
  buildPrimIndexBuffer();
  createPrimVertexDecl();
  createPrimFX();

  createMeshFX();

  for (std::vector<Content::CAnimatedMesh*>::iterator it = pMeshes->begin(); it != pMeshes->end(); ++it)
  {
    (*it)->onResetDevice();
    (*it)->Effect=pMeshEffect;
  }

  for (std::vector<GUI::CGUIObject*>::iterator it = pGUIObjects->begin();it != pGUIObjects->end();++it)
  {
    (*it)->onResetDevice();
  }

	fps->onResetDevice(pD3DDevice);
}

//kamera beállítása
void CRenderer::setCamera(Content::CCamera* camera)
{
	this->pCamera=camera;
}

void CRenderer::buildPrimVertexBuffer()
{
  if (!SUCCEEDED(pD3DDevice->CreateVertexBuffer(numPrimVertices*sizeof(PrimitiveVertex),
                               D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY,
                               PRIMITIVEFVF,
                               D3DPOOL_DEFAULT,
                               &pPrimVBuffer,
                               NULL)))
  {
    LOG_ERROR("Nem sikerult felepiteni a vertex buffert. Kilepes...")
    exit(1);
  }

	void* pVoid=NULL;
  int totalVert = 0;
  pPrimVBuffer->Lock(0,numPrimVertices*sizeof(PrimitiveVertex),&pVoid,NULL);

  //LOG_INFO("lock megy")
  for (std::vector<Content::CPrimitive*>::iterator it = pPrimitives->begin();
    it != pPrimitives->end(); it++)
  {
    int nVert= (*it)->getNumVertices();
    int size = nVert*sizeof(PrimitiveVertex);
    memcpy((PrimitiveVertex*)pVoid+totalVert,(*it)->getVertices(), size);
    totalVert+=nVert;
    /*
    for (int i=0;i < nVert;++i)
    {
      LOG_INFO(i << ".vertex: \n" << (*it)->getVertices()[i].x << "\n" << (*it)->getVertices()[i].y << "\n" << (*it)->getVertices()[i].z << "\n")
    }
    */
    
  }

  pPrimVBuffer->Unlock();

  //LOG_INFO("Primitive VertexBuffer epitese kesz.")

}

void CRenderer::buildPrimIndexBuffer()
{
  if (!SUCCEEDED(pD3DDevice->CreateIndexBuffer(numPrimIndices*sizeof(WORD),
                                     D3DUSAGE_WRITEONLY,
                                     D3DFMT_INDEX16,
                                     D3DPOOL_DEFAULT,
                                     &pPrimIBuffer,
                                     NULL)))
  {
    LOG_ERROR("Nem sikerult felepiteni az index buffert. Kilepes...")
    exit(1);
  }

	void* pVoid=NULL;
  int totalInd = 0;
  pPrimIBuffer->Lock(0,numPrimIndices*sizeof(WORD),&pVoid,NULL);

  for (std::vector<Content::CPrimitive*>::iterator it = pPrimitives->begin();
  it != pPrimitives->end(); it++)
  {
    int nInd= (*it)->getNumIndices();
    int size = nInd*sizeof(WORD);
    memcpy((WORD*)pVoid+totalInd,(*it)->getIndices(),size);
    totalInd+=nInd;

    int nt = (*it)->getNumTriangles();
    /*for (int i=0;i < nt;++i)
    {
      int j=i*3;
      LOG_INFO(i << ".face: \n" << (*it)->getIndices()[j] << "\n" << (*it)->getIndices()[j+1] << "\n" << (*it)->getIndices()[j+2] << "\n")
    }*/

    //LOG_INFO(nInd << "\n" << size)

  }
  pPrimIBuffer->Unlock();
  //LOG_INFO("Primitive IndexBuffer epitese kesz.")

}

void CRenderer::renderSkyBox()
{
  initSkyEffect();

  pD3DDevice->SetStreamSource(0, pPrimVBuffer, 0, sizeof(PrimitiveVertex));
  pD3DDevice->SetVertexDeclaration(pPrimVertexDecl);
  pD3DDevice->SetIndices(pPrimIBuffer);

  D3DXMATRIX matView = (*pCamera->getViewMatrix());

  std::vector<Content::CPrimitive*>::iterator it = pPrimitives->begin();

    float x,y,z;
    (*it)->getPos(x,y,z);
    float yaw,pitch,roll;
    (*it)->getOrientation(yaw,pitch,roll);
    
    D3DXMATRIX matRot;
    D3DXMatrixRotationYawPitchRoll(&matRot,yaw,pitch,roll);
    D3DXMATRIX matTransl;
    D3DXMatrixTranslation(&matTransl,x,y,z);
    D3DXMATRIX matWorld = matRot*matTransl;

    D3DXMATRIX mViewProj=matView*matProj;
  
    pPrimEffect->SetMatrix(hWVP, &mViewProj);
    pPrimEffect->SetMatrix(hWorld, &matWorld);
      pPrimEffect->CommitChanges();


    
    int totalVert = 0;
    int totalInd = 0;

	  UINT passCnt = 0;
	  pPrimEffect->Begin( &passCnt, 0 );
	  for( UINT p = 0; p < passCnt; ++p )
	  {
      int nVert= (*it)->getNumVertices();
      int nInd= (*it)->getNumIndices();
      int nTriangles = (*it)->getNumTriangles();
      int offset = totalVert;
      pPrimEffect->BeginPass( p );
      pPrimEffect->SetTexture(hCubeTex,pSkyBox->getCubeTexture());
      pPrimEffect->CommitChanges();
      if (!SUCCEEDED(pD3DDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,totalVert,0,nVert,totalInd,nTriangles)))
      {
          LOG_ERROR("Hiba a primitive-k rajzolasakor")
      }

		  pPrimEffect->EndPass();
      
      totalVert+=nVert;
      totalInd+=nInd;
/*      
      LOG_INFO("nVert: " << nVert << "\n")
      LOG_INFO("nInd: "<< nInd << "\n")
      LOG_INFO("nTriangles: " << nTriangles << "\n")
      LOG_INFO("offset: " << offset << "\n")
      LOG_INFO("TotalVert: " << totalVert << "\n")
      LOG_INFO("TotalInd: " << totalInd << "\n")
  */   
     
	  }
	  pPrimEffect->End();
    
    
}

void CRenderer::renderPrimitives()
{
  initPrimEffect();


  //LOG_INFO("renderPrimitives\n")
  pD3DDevice->SetStreamSource(0, pPrimVBuffer, 0, sizeof(PrimitiveVertex));
  pD3DDevice->SetVertexDeclaration(pPrimVertexDecl);
  pD3DDevice->SetIndices(pPrimIBuffer);
  //pD3DDevice->SetFVF(PRIMITIVEFVF);

  D3DXMATRIX matView = (*pCamera->getViewMatrix());

  float camX,camY,camZ;
  pCamera->getPos(camX,camY,camZ);
  D3DXVECTOR3 camPos = D3DXVECTOR3(camX,camY,camZ);
  pPrimEffect->SetValue(hCameraPos, &camPos , sizeof(D3DXVECTOR3) );

  pPrimEffect->SetValue(hLightColor, &lightColor,	sizeof(D3DXCOLOR));
	pPrimEffect->SetValue(hLightPos, &lightPos, sizeof(D3DXVECTOR3));

  pPrimEffect->SetValue(hSpecularMaterialColor, &primMat.specularMat, sizeof(D3DXCOLOR));
  pPrimEffect->SetFloat( hSpecularPower, primMat.specularPower);
    int totalVert = 0;
    int totalInd = 0;

  std::vector<Content::CPrimitive*>::iterator it = pPrimitives->begin();
  if (pSkyBox)
  {
    totalVert += pSkyBox->getNumVertices();
    totalInd += pSkyBox->getNumIndices();
    it++;
  }
  for (it ;it != pPrimitives->end(); it++)
  {
    float x,y,z;
    (*it)->getPos(x,y,z);
    float yaw,pitch,roll;
    (*it)->getOrientation(yaw,pitch,roll);
    
    D3DXMATRIX matRot;
    D3DXMatrixRotationYawPitchRoll(&matRot,yaw,pitch,roll);
    D3DXMATRIX matTransl;
    D3DXMatrixTranslation(&matTransl,x,y,z);
    D3DXMATRIX matWorld = matRot*matTransl;

    D3DXMATRIX mWVP=matWorld*matView*matProj;
  
    pPrimEffect->SetMatrix(hWVP, &mWVP);
    pPrimEffect->SetMatrix(hWorld, &matWorld);
	
      int r,g,b;
      (*it)->getColor(r,g,b);
      primMat.ambientMat= D3DCOLOR_XRGB(r, g, b);
      primMat.diffuseMat= D3DCOLOR_XRGB(r, g, b);

      
      pPrimEffect->SetValue(hAmbientMaterialColor,	&primMat.ambientMat,		sizeof(D3DXCOLOR));
      pPrimEffect->SetValue(hDiffuseMaterialColor,	&primMat.diffuseMat,		sizeof(D3DXCOLOR));
      pPrimEffect->CommitChanges();


    


	  UINT passCnt = 0;
	  pPrimEffect->Begin( &passCnt, 0 );
	  for( UINT p = 0; p < passCnt; ++p )
	  {
      int nVert= (*it)->getNumVertices();
      int nInd= (*it)->getNumIndices();
      int nTriangles = (*it)->getNumTriangles();
      int offset = totalVert;
      pPrimEffect->BeginPass( p );
      pPrimEffect->CommitChanges();
      if ((*it)->isVisible())
      {
        if (!SUCCEEDED(pD3DDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,totalVert,0,nVert,totalInd,nTriangles)))
        {
            LOG_ERROR("Hiba a primitive-k rajzolasakor")
        }
      }

		  pPrimEffect->EndPass();
      
      totalVert+=nVert;
      totalInd+=nInd;
/*      
      LOG_INFO("nVert: " << nVert << "\n")
      LOG_INFO("nInd: "<< nInd << "\n")
      LOG_INFO("nTriangles: " << nTriangles << "\n")
      LOG_INFO("offset: " << offset << "\n")
      LOG_INFO("TotalVert: " << totalVert << "\n")
      LOG_INFO("TotalInd: " << totalInd << "\n")
  */   
     
	  }
	  pPrimEffect->End();
    
    
  }
}






void CRenderer::renderMeshes()
{

  initMeshEffect();
  D3DXMATRIX matView = (*pCamera->getViewMatrix());

  float camX,camY,camZ;
  pCamera->getPos(camX,camY,camZ);
  D3DXVECTOR3 camPos = D3DXVECTOR3(camX,camY,camZ);

  pPrimEffect->SetValue(hCameraPos, &camPos , sizeof(D3DXVECTOR3) );

  pPrimEffect->SetValue(hLightColor, &lightColor,	sizeof(D3DXCOLOR));
	pPrimEffect->SetValue(hLightPos, &lightPos, sizeof(D3DXVECTOR3));

  for (std::vector<Content::CAnimatedMesh*>::iterator it = pMeshes->begin();
    it != pMeshes->end(); it++)
  {
    if (!(*it)->isVisible())
    {
      continue;
    }
    float x,y,z;
    (*it)->getPos(x,y,z);
    float yaw,pitch,roll;
    (*it)->getOrientation(yaw,pitch,roll);
      if (!(*it)->Effect)
      {
        (*it)->Effect = pMeshEffect;
      }
    
    D3DXMATRIX matRot;
    D3DXMatrixRotationYawPitchRoll(&matRot,yaw,pitch,roll);

    D3DXMATRIX matTransl;
    D3DXMatrixTranslation(&matTransl,x,y,z);

    D3DXMATRIX matWorld = matRot*matTransl;
  //  pMeshEffect->SetMatrix(hWorld, &matWorld);
	
    D3DXMATRIX matViewProj = matView*matProj;
	  pMeshEffect->SetMatrix("matViewProj", &matViewProj);

    (*it)->Update(pTimer->getElapsedTime(),&matWorld);

    


    pMeshEffect->CommitChanges();
      (*it)->Draw();
   
    
  }

}

void CRenderer::setPrimitiveQueue(std::vector<Content::CPrimitive*>* pPrim)
{
  pPrimitives = pPrim;
  pPrimitives->push_back(pSkyBox);
}

void CRenderer::setMeshQueue(std::vector<Content::CAnimatedMesh*>* pMeshes_in)
{
  pMeshes = pMeshes_in;
}

void CRenderer::setGUIQueue(std::vector<GUI::CGUIObject*>* pGUIObjects_in)
{
  pGUIObjects = pGUIObjects_in;
}


void CRenderer::createPrimVertexDecl()
{
	D3DVERTEXELEMENT9 vertexElements[] = 
	{
		{0, 0,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
		{0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0},
		{0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
		D3DDECL_END()
	};


	if (!SUCCEEDED(pD3DDevice->CreateVertexDeclaration( vertexElements, &pPrimVertexDecl)))
  {
    LOG_ERROR("Vertex deklaracio sikertelen. Kilepes")
    exit(1);
  }

}

void CRenderer::createPrimFX()
{
  ID3DXBuffer* pErrorBuffer;

	const std::string file=".\\Effects\\primitives.fx";
	if (!fileExists(file))
  {
    LOG_ERROR("Nem letezik a primitives.fx! Kilepes.");
    exit(1);
  }

	if (!SUCCEEDED(D3DXCreateEffectFromFileA( pD3DDevice, 
							file.c_str(), 
							  0, 
							  0, 
							  0/*/D3DXSHADER_DEBUG*/, 
							  0, 
							  &pPrimEffect, 
							  &pErrorBuffer
							)))
  {
	  // effekt betöltési hiba
    LOG_ERROR("Nem sikerult a primitives.fx betoltese. Kilepes")
	  if( pErrorBuffer )
	  {
		  MessageBox(0, reinterpret_cast<LPCSTR>(pErrorBuffer->GetBufferPointer()), 0, 0);
		  exit(1);
	  }
  }
  LOG_INFO("primitves.fx letrehozva.")
}

void CRenderer::createMeshFX()
{
  ID3DXBuffer* pErrorBuffer;

	const std::string file=".\\Effects\\meshes.fx";
	if (!fileExists(file))
  {
    LOG_ERROR("Nem letezik a primitives.fx! Kilepes.");
    exit(1);
  }

	if (!SUCCEEDED(D3DXCreateEffectFromFileA( pD3DDevice, 
							file.c_str(), 
							  0, 
							  0, 
							  0/*/D3DXSHADER_DEBUG*/, 
							  0, 
							  &pMeshEffect, 
							  &pErrorBuffer
							)))
  {
	  // effekt betöltési hiba
    LOG_ERROR("Nem sikerult a meshes.fx betoltese. Kilepes")
	  if( pErrorBuffer )
	  {
		  MessageBox(0, reinterpret_cast<LPCSTR>(pErrorBuffer->GetBufferPointer()), 0, 0);
		  exit(1);
	  }
  }
  LOG_INFO("meshes.fx letrehozva.")
}

void CRenderer::initSkyEffect()
{
	hTech = pPrimEffect->GetTechniqueByName("SkyBoxTech");
	hWVP = pPrimEffect->GetParameterByName(0, "gWorldViewProjection");
	hWVP = pPrimEffect->GetParameterByName(0, "gViewProj");
	hWorld  = pPrimEffect->GetParameterByName(0, "gWorld");

	hAmbientMaterialColor	= pPrimEffect->GetParameterByName(0, "gAmbientMaterialColor");
	hDiffuseMaterialColor	= pPrimEffect->GetParameterByName(0, "gDiffuseMaterialColor");

	hCubeTex = pPrimEffect->GetParameterByName(0, "gSkyBox");
	
	if ( hTech == NULL
		|| hViewProj == NULL
		|| hWorld == NULL
		|| hLightColor == NULL
		|| hLightPos == NULL
		|| hAmbientMaterialColor == NULL
		|| hDiffuseMaterialColor == NULL
		|| hSpecularMaterialColor == NULL
		|| hSpecularPower == NULL
		|| hDT == NULL
		|| hCameraPos == NULL
		|| hCubeTex == NULL)
	{
		LOG_ERROR( "Effekt paraméter kezelo lekeresi hiba! Kilepes." );
		exit(1);
	}
  if (!SUCCEEDED(pPrimEffect->SetTechnique(hTech)))
  {
		LOG_ERROR( "Effekt beallitasi hiba! Kilepes." );
		exit(1);
  }
}

void CRenderer::initPrimEffect()
{
	// kezelők lekérdezése
	hTech = pPrimEffect->GetTechniqueByName("PrimitiveTech");
	hWVP = pPrimEffect->GetParameterByName(0, "gWorldViewProjection");
	hWorld  = pPrimEffect->GetParameterByName(0, "gWorld");
	hLightColor = pPrimEffect->GetParameterByName(0, "gLightColor");
	hLightPos = pPrimEffect->GetParameterByName(0, "gLightPos");

	hAmbientMaterialColor	= pPrimEffect->GetParameterByName(0, "gAmbientMaterialColor");
	hDiffuseMaterialColor	= pPrimEffect->GetParameterByName(0, "gDiffuseMaterialColor");

	hSpecularMaterialColor = pPrimEffect->GetParameterByName(0, "gSpecularMaterialColor");
	hSpecularPower = pPrimEffect->GetParameterByName(0, "gSpecularParam" );

	hDT = pPrimEffect->GetParameterByName(0, "gDT");

	
	hCameraPos = pPrimEffect->GetParameterByName(0, "gCameraPos");
	
	hTex0 = pPrimEffect->GetParameterByName(0, "gTex0");
	
	if ( hTech == NULL
		|| hWVP == NULL
		|| hWorld == NULL
		|| hLightColor == NULL
		|| hLightPos == NULL
		|| hAmbientMaterialColor == NULL
		|| hDiffuseMaterialColor == NULL
		|| hSpecularMaterialColor == NULL
		|| hSpecularPower == NULL
		|| hDT == NULL
		|| hCameraPos == NULL
		|| hTex0 == NULL)
	{
		LOG_ERROR( "Effekt paraméter kezelo lekeresi hiba! Kilepes." );
		exit(1);
	}
  if (!SUCCEEDED(pPrimEffect->SetTechnique(hTech)))
  {
		LOG_ERROR( "Effekt beallitasi hiba! Kilepes." );
		exit(1);
  }
  //LOG_INFO("Sikeres primitive effekt beallitas")
	
}


void CRenderer::initMeshEffect()
{
	// kezelők lekérdezése
	hWorld  = pMeshEffect->GetParameterByName(0, "matWorld");
	hLightColor = pMeshEffect->GetParameterByName(0, "gLightColor");
	hLightPos = pMeshEffect->GetParameterByName(0, "gLightPos");

	hAmbientMaterialColor	= pMeshEffect->GetParameterByName(0, "gAmbientMaterialColor");
	hDiffuseMaterialColor	= pMeshEffect->GetParameterByName(0, "gDiffuseMaterialColor");

	hSpecularMaterialColor = pMeshEffect->GetParameterByName(0, "gSpecularMaterialColor");
	hSpecularPower = pMeshEffect->GetParameterByName(0, "gSpecularParam" );

	hCameraPos = pMeshEffect->GetParameterByName(0, "gCameraPos");
	if ( hWorld == NULL
		|| hLightColor == NULL
		|| hLightPos == NULL
		|| hAmbientMaterialColor == NULL
		|| hDiffuseMaterialColor == NULL
		|| hSpecularMaterialColor == NULL
		|| hSpecularPower == NULL
		|| hCameraPos == NULL)
	{
		LOG_ERROR( "Effekt paraméter kezelo lekeresi hiba! Kilepes." );
		exit(1);
	}
/*  if (!SUCCEEDED(pMeshEffect->SetTechnique(hTech)))
  {
		LOG_ERROR( "Effekt beallitasi hiba! Kilepes." );
		exit(1);
  }*/
  //LOG_INFO("Sikeres primitive effekt beallitas")
	
}

void CRenderer::releaseBuffers()
{
  SAFE_RELEASE(pPrimVBuffer);
  SAFE_RELEASE(pPrimIBuffer);
}

void CRenderer::rebuildBuffers()
{
  releaseBuffers();

  for (std::vector<Content::CPrimitive*>::iterator it = pPrimitives->begin(); it != pPrimitives->end();++it)
  {
    
    numPrimVertices += (*it)->getNumVertices();
    numPrimIndices += (*it)->getNumIndices();
    numPrimTriangles += (*it)->getNumTriangles();
  }
/*    for (int i=0;i < 24;++i)
    {
      LOG_INFO(i << ".vertex: \n" << primitive->getVertices()[i].x << "\n" << primitive->getVertices()[i].y << "\n" << primitive->getVertices()[i].z << "\n")
    }
    */

  buildPrimVertexBuffer();
  buildPrimIndexBuffer();
}

void CRenderer::renderGUI()
{
  for (std::vector<GUI::CGUIObject*>::iterator it = pGUIObjects->begin();it!= pGUIObjects->end();++it)
  {
    (*it)->render();
  }
}